//
//  AddressBookVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/15.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya

class AddressBookVC: BaseVC {

    fileprivate var sortChatUsers: [[ChatUser]] = []
    fileprivate var titles: [String] = []

    fileprivate var searchView: SJSearchBar!
    fileprivate var tableView: UITableView!

    fileprivate var canclePull: Cancellable?

    fileprivate var searchResultVC = SearchResultVC()

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        blueNavigationBackgroud()
        create()
        
        runInBackground {
            let sortData = AddressBookHelper.sortUser(chatUsers: SJCache.chatUsers)
            self.sortChatUsers = sortData.0
            self.titles = sortData.1
            runOnMainThread {
                self.tableView.reloadData()
            }
            self.pullData()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(change), name: NSNotification.Name.changeCompany.changeCompanyUpdateData, object: nil)
        
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        GlobalConfig.baiduStatisticsPageViewStart("通讯录")
    }
  
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalConfig.baiduStatisticsPageViewEnd("通讯录")
    }
  
  
    deinit {
        canclePull?.cancel()
    }

    
    @objc func change() {
        pullData()
    }
    
}

// MARK: - fileprivate
extension AddressBookVC {
  
    fileprivate func pullData() {
        canclePull = UserRequest.shared.getUserAddressBook { (chatUsers) in
            runInBackground {
                SJCache.chatUsers = chatUsers
            }
          
            runOnMainThread {
                let sortData = AddressBookHelper.sortUser(chatUsers: chatUsers)
                self.sortChatUsers = sortData.0
                self.titles = sortData.1
                self.tableView.reloadData()
            }
        }
    }
  
    @objc func noticeNext() {
        let noticeVC = NoticeVC()
        noticeVC.refreshBefore = {
            //self.redPoint.isHidden = true
        }
        navigationController?.pushViewController(noticeVC, animated: true)
    }
    
    fileprivate func create() {
        title = "通讯录"
        view.backgroundColor = GlobalConfig.BGWhiteColor
        
        let noticeButton = UIButton()
        noticeButton.frame = SJApp.bounds(width: 30, height: 44)
        noticeButton.addTarget(self, action: #selector(noticeNext), for: .touchUpInside)
        let noticeImage = UIImage(named: "nav-message-icon")
        noticeButton.setImage(noticeImage, for: .normal)
        noticeButton.contentHorizontalAlignment = .right
        let noticeItem = UIBarButtonItem(customView: noticeButton)
        let spaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spaceItem.width = -5
        
        navigationItem.rightBarButtonItems = [spaceItem,noticeItem]
        
        
        
        addBackItem()

        searchResultVC.selectModel = { [unowned self] (model) in
          
          self.searchView.set(isEditing: false)
          self.didEndSearch()
          
          
        }

        searchView = SJSearchBar()
        searchView.placeholder = "搜索"
        searchView.delegate = self
        searchView.isLeft = true
        view.addSubview(searchView)

        tableView = UITableView()
        tableView.backgroundColor = UIColor.clear
        tableView.frame = CGRect(x: 0, y: 44, width: UIScreen.width, height: UIScreen.height - 64 - 44)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.sectionIndexColor = GlobalConfig.BGSkyBlueColor
        tableView.sectionIndexBackgroundColor = UIColor.clear
        tableView.rowHeight = AddressBookCell.height
        tableView.sectionHeaderHeight = 37
        tableView.register(AddressBookCell.self, forCellReuseIdentifier: AddressBookCell.identifier)
        view.addSubview(tableView)
    }
}

// MARK: - SJSearchBarDelegate
extension AddressBookVC: SJSearchBarDelegate {
  
    func didBeaginSearch() {
        self.view.addSubview(searchResultVC.view)
        navigationController?.setNavigationBarHidden(true, animated: true)
        UIView.animate(withDuration: 0.2) {
          self.searchView.sj.top = 20
          self.tableView.sj.top = 64
          self.searchResultVC.view.sj.top = 64
        }
    }
  
    func didEndSearch() {
        self.searchView.sj.top = 0
        self.tableView.sj.top = 44
        searchResultVC.models = []
        searchResultVC.view.removeFromSuperview()
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
  
    func didChange(text: String) {
        let users = SJCache.chatUsers
        let filterUsers = users.filter { (user) -> Bool in
            if user.nickname.contains(text) { return true }
            else if user.phoneNumber.contains(text) { return true }
            return false
        }
        searchResultVC.models = filterUsers
    }
}

// MARK: - UITableViewDataSource
extension AddressBookVC : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return titles.count }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sortChatUsers[section].count }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AddressBookCell.identifier) as! AddressBookCell
        cell.chatUser = sortChatUsers[indexPath.section][indexPath.row]
        return cell
    }
}

// MARK: - UITableViewDelegate
extension AddressBookVC : UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = SectionV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 37))
        view.title = titles[section]
        return view
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        /*
        let vc = ChatUserInfoVC()
        vc.model = sortChatUsers[indexPath.section][indexPath.row]
        vc.type = .address
        navigationController?.pushViewController(vc, animated: true)
 */
    }

    func sectionIndexTitles(for tableView: UITableView) -> [String]? { return titles }
}
